package Server;

import CommonOperationsClientServer.FilesOperations;
import CommonOperationsClientServer.OperationsRefactor;
import Users.User;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;

public class UsersOperationsServer {

    public static void createNewUser(User user, String usersFile, BufferedReader input, PrintWriter output,
            boolean initServer) {
        ArrayList<User> users = listOfUsers(usersFile);
        Iterator it = users.iterator();
        boolean usersNoExists = true;
        while (it.hasNext() && usersNoExists) {
            User userAux = (User) it.next();
            if (userAux.getUserName().equals(user.getUserName())) {
                usersNoExists = false;
            }
        }
        if (usersNoExists) {
            users.add(user);
            updateUserList(users, usersFile);
            if (!initServer) {
                OperationsRefactor.outputMessage(output, "usercreated");
            }
        } else {
            if (!initServer) {
                OperationsRefactor.outputMessage(output, "userexist");
            }
        }
    }

    public static void deleteUser(String usersFile, BufferedReader input, PrintWriter output) {
        try {
            String userToDelete = input.readLine();
            if (!userToDelete.equals("cancelOperation")) {
                User user = User.stringToUser(userToDelete);
                ArrayList<User> users = listOfUsers(usersFile);
                if (users.contains(user)) {
                    users.remove(user);
                    OperationsRefactor.outputMessage(output, "userdeleted");
                    updateUserList(users, usersFile);
                } else {
                    OperationsRefactor.outputMessage(output, "usernotexists");
                }
            }
        } catch (Exception e) {
        }
    }

    public static ArrayList<User> listOfUsers(String usersFile) {
        ArrayList<User> userList = new ArrayList();
        File f;
        FileReader fr = null;
        BufferedReader br = null;
        try {
            f = new File(usersFile);
            fr = new FileReader(f);
            br = new BufferedReader(fr);
            String line;
            while ((line = br.readLine()) != null) {
                if (line.contains(";")) {
                    userList.add(User.stringToUser(line));
                }
            }
        } catch (Exception e) {
        } finally {
            OperationsRefactor.closeReadFile(fr, br);
        }
        return userList;
    }

    private static void updateUserList(ArrayList<User> users, String usersFile) {
        File f = new File(usersFile);
        FileWriter fw = null;
        PrintWriter pw = null;
        if (f.exists() && f.isFile()) {
            try {
                f.delete();
                f.createNewFile();
                Iterator it = users.iterator();
                fw = new FileWriter(f);
                pw = new PrintWriter(fw, true);
                while (it.hasNext()) {
                    User user = User.stringToUser(it.next().toString());
                    pw.write(user.toString());
                    pw.flush();
                    pw.write('\n');
                    pw.flush();
                }
            } catch (Exception e) {
            } finally {
                OperationsRefactor.closeWriteFile(fw, pw);
            }
        }
    }

    public static User receiveUser(User user, String usersFile, PrintWriter output) {
        ArrayList<User> usersList = listOfUsers(usersFile);
        User userAux = null;
        String user_name = user.getUserName();
        String user_pass = user.getUserPass();
        Iterator it = usersList.iterator();
        boolean continueList = true;
        while (it.hasNext() && continueList) {
            userAux = (User) it.next();
            if (userAux.getUserName().equals(user_name) && userAux.getUserPass().equals(user_pass)) {
                continueList = false;
            }
        }
        if (!user.equals(userAux)) {
            userAux = null;
        }
        sendPrivilegesUser(userAux, output);
        return userAux;
    }

    public static void sendPrivilegesUser(User user, PrintWriter output) {
        if (user == null) {
            OperationsRefactor.outputMessage(output, "userNotFound");
        } else {
            boolean user_privileged = user.getUserPrivileged();
            output.println(user_privileged);
            output.flush();
        }
    }

    public static void receiveCommand(String command, PrintWriter output) {
        String response = FilesOperations.executeCommand(command);
        output.println(response.length());
        output.flush();
        output.print(response);
        output.flush();
    }
}
